/**
 * 
 */
package com.edou.base.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;

/**
 * @author root
 *
 */
public class HttpClientUtil {
	
	protected static Log logger = LogFactory.getLog(HttpClientUtil.class);
	
	/**
	 * 下载文件
	 * @param url
	 * @param filePath
	 */
	public static boolean HttpClientPostDownFile(String url,String filePath,List<NameValuePair> nvps){
		boolean isSuccess = false;
		/* 1 生成 HttpClinet 对象并设置参数 */
		CloseableHttpClient httpClient = HttpClients.createDefault();
		/* 2创建post请求*/
		HttpPost post = new HttpPost(url);
        try {
        	if(nvps != null && nvps.size() > 0){
        		post.setEntity(new UrlEncodedFormEntity(nvps));
        	}
		} catch (Exception e1) {
			e1.printStackTrace();
		}  
		/* 3设置请求配置*/
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10).setConnectTimeout(1000 * 60 * 10).build();
		post.setConfig(requestConfig);
		//输出流对象
		FileOutputStream os = null;
		//输入流对象
		InputStream inStream = null;
		try {
			/* 3执行请求*/
			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();  
		    if (entity != null) {  
		    	int statusCode = response.getStatusLine().getStatusCode();
		    	if(statusCode == HttpStatus.SC_OK){
		    		inStream = entity.getContent();  
		        	byte[] buf = new byte[2048000];
					/* 创建输出流 */
		        	os = new FileOutputStream(filePath);
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						os.write(buf, 0, readLength);
					}
					isSuccess = true;
		    	}
		    }  
		    response.close();
		} catch (Exception e) {
			
		}finally{
			try {
				if(null != inStream){
					inStream.close();
				}
				if(null != os){
					os.close();
				}
				HttpClientUtils.closeQuietly(httpClient);
			} catch (IOException e) {
				
			}  
		}
		return isSuccess;
	}
	
	
	/**
	 * 发送JSON数据，POST方式
	 * @param data
	 */
	public static String postJSONData(String url,JSONObject data) throws Exception{
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		String inputParam = data.toJSONString();
		logger.debug("POST接口发送内容："+inputParam);
		httpPost.setEntity(new StringEntity(inputParam, "UTF-8"));
		CloseableHttpResponse response = null;
		
		String result = null;
		try{
			response = httpclient.execute(httpPost);
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
			logger.debug("发送POST接口数据返回内容："+result);
		}catch(Exception ex){
			logger.debug("调用POST接口数据时发生异常：");
			throw new Exception(ex.getMessage());
		}finally{
			if(null != response){
				try{
					response.close();
				}catch(Exception e){}
			}
		}
		
		return result;
		
	}
	
	/**
	 * 发送POST请求参数
	 * @param url
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public static String postData(String url,Map<String,String> paramMap) throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			logger.debug("POST请求地址：" + url);
			logger.debug("POST请求内容：" + paramMap);
			// 构造请求
			HttpPost httpPost = new HttpPost(url);
			/* 3设置请求配置*/
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10).setConnectTimeout(1000 * 60 * 10).build();
			httpPost.setConfig(requestConfig);
			// 封装参数
			List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
			if(null != paramMap){
				for(Entry<String,String> item : paramMap.entrySet()){
					nvps.add(new BasicNameValuePair(item.getKey(),item.getValue()));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
			
			
			
			// 发起请求
			response = httpClient.execute(httpPost);
			// 获取响应数据
			result = EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
			logger.debug("接收到的POST响应内容：" + result);
			httpPost.abort();
		} catch (Exception ex) {
			String msg = "POST请求发送失败:";
			logger.error(msg);
			throw new Exception(ex.getMessage());
		} finally {
			try {
				response.close();
				HttpClientUtils.closeQuietly(httpClient);
			} catch (Exception e) {}
		}
		return result;
	} 
	
	/**
	 * 发送POST请求参数，加入请求body中
	 * @param url
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public static String postDataInBody(String url,String bodyContent) throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			logger.debug("POST请求地址：" + url);
			logger.debug("POST请求内容：" + bodyContent);
			// 构造请求
			HttpPost httpPost = new HttpPost(url);
			/* 3设置请求配置*/
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10).setConnectTimeout(1000 * 60 * 10).build();
			httpPost.setConfig(requestConfig);
			
			//构造请求body
			httpPost.setEntity(new StringEntity(bodyContent, "UTF-8"));
			
			// 发起请求
			response = httpClient.execute(httpPost);
			// 获取响应数据
			result = EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
			logger.debug("接收到的POST响应内容：" + result);
			httpPost.abort();
		} catch (Exception ex) {
			String msg = "POST请求发送失败:" + ex.getMessage();
			logger.error(msg,ex);
			throw new Exception(ex.getMessage());
		} finally {
			try {
				response.close();
				HttpClientUtils.closeQuietly(httpClient);
			} catch (Exception e) {}
		}
		return result;
	}
	
	
	/**
	 * GET请求获取数据
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getData(String url) throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			logger.debug("GET请求地址：" + url);
			// 构造请求
			HttpGet httpGet = new HttpGet(url);
			/* 3设置请求配置*/
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10).setConnectTimeout(1000 * 60 * 10).build();
			httpGet.setConfig(requestConfig);
			
			// 发起请求
			response = httpClient.execute(httpGet);
			// 获取响应数据
			result = EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
			logger.debug("接收到的GET响应内容：" + result);
			httpGet.abort();
		} catch (Exception ex) {
			String msg = "GET请求发送失败:" + ex.getMessage();
			logger.error(msg,ex);
			throw new Exception(ex);
		} finally {
			try {
				response.close();
				HttpClientUtils.closeQuietly(httpClient);
			} catch (Exception e) {}
		}
		return result;
	} 
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {
		JSONObject json = new JSONObject();
		json.put("sign", "EF9625CFC2885FA84456AD88C83AB134");
		json.put("sessionkey", "50b24306aacf479a9a5651f0fc7cabc3");
		json.put("appkey", "112194");
		json.put("method", "gy.erp.items.get");
		
		String reqBody = json.toJSONString();
		String resContent = HttpClientUtil.postDataInBody("http://v2.api.guanyierp.com/rest/erp_open", reqBody);
		System.out.println(resContent);
		
	}
	
}
